package com.boshanam.view.actions.user;

import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.boshanam.exceptions.domain.user.EmailIdAlreadyRegisteredException;
import com.boshanam.exceptions.domain.user.UserAlreadyExistException;
import com.boshanam.exceptions.domain.user.UserNameAlreadyExistsException;
import com.boshanam.model.vos.domain.user.UserVO;
import com.boshanam.model.vos.domain.user.UserVOImmutable;
import com.boshanam.service.user.IUserService;
import com.boshanam.view.forms.user.UserRegForm;

/**
 * @author Sivakumar Y, UserRegAction.java Jan 5, 2010 11:08:39 PM
 *         www.ibigbang.net shiva.forums@gmail.com
 */
public class UserRegAction extends Action {

	Log log = LogFactory.getLog(UserRegAction.class);

	private IUserService userService;

	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if (isCancelled(request)) {
			return mapping.findForward("welcome");
		}
		ActionMessages errors = new ActionMessages();

		UserRegForm userForm = (UserRegForm) form;
		UserVO user = userForm.getUser();
		
		Locale userLocale = request.getLocale();
		if(isEmptyLocale(userLocale)){
			@SuppressWarnings("unchecked")
			Enumeration<Locale> locales = request.getLocales();
			while(locales.hasMoreElements()){
				userLocale = locales.nextElement();
				if(!isEmptyLocale(userLocale)){
					break;
				}
			}
		}
		if(isEmptyLocale(userLocale)){
			log.error("Unable to get User Locale Information..., Stting to Locale.US default locale...");
			userLocale = Locale.US;
		}
		log.fatal("The Locale associated with user: " + userLocale);
		user.getUserSettings().setLocale(userLocale);
		user.setAccountNonExpired(true);
		user.setAccountNonLocked(true);
		user.setCredentialsNonExpired(true);
		user.setEnabled(true);

	/*	if (true) {
			log.info(user.toString());
			return mapping.findForward("regSuccess");
		}*/

		try {
			userService.createUser(user);
		} catch (EmailIdAlreadyRegisteredException e) {
			log.info("User Registration Failed: Email already registered: ", e);
			errors.add("email", new ActionMessage("errors.email.alreadyregistered"));
		} catch (UserNameAlreadyExistsException e) {
			log.info("User Registration Failed: Username already registered: ",	e);
			errors.add("email", new ActionMessage("errors.email.alreadyregistered"));
		} catch(UserAlreadyExistException e){
			errors.add("email", new ActionMessage("errors.username.email.alreadyregistered"));
		} catch (Exception e) {
			log.error("User Registration Failed: Unknown Error", e);
			errors.add("email", new ActionMessage("application.unknown.exception"));
		}
		if(!errors.isEmpty()){
			this.saveErrors(request, errors);
			return (mapping.getInputForward());
		} else {
			try {
				List<UserVOImmutable> list = userService.getAllUsers();
				request.setAttribute("REG_USER_LIST", list);
			} catch (Exception e) {
				log.error("Unable to Load Users From Datastore...", e);
			}
		}

		return mapping.findForward("regSuccess");
	}


	/**
	 * Returns whether the locale is empy i.e., Locale has no language Set to it.
	 * @param userLocale
	 * @return
	 */
	private boolean isEmptyLocale(Locale userLocale) {
		if(userLocale == null || userLocale.getLanguage() == null || userLocale.getLanguage().equals("")){
			return true;
		}
		return false;
	}


	/**
	 * @param userService the userService to set
	 */
	public void setUserService(IUserService iUserService) {
		this.userService = iUserService;
	}

	/**
	 * @return the userService
	 */
	public IUserService getUserService() {
		return userService;
	}

}
